package elearning.json.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.opensymphony.xwork2.ActionSupport;

import elearning.category.entity.Category;
import elearning.category.service.CategoryService;
import elearning.categorysecond.entity.CategorySecond;
import elearning.json.entity.IndexRec;
import elearning.json.service.IndexRecService;

public class IndexAction extends ActionSupport{

	private IndexRecService indexRecService;
	private CategoryService categoryService;
	

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}
	public void setIndexRecService(IndexRecService indexRecService) {
		this.indexRecService = indexRecService;
	}
	public void nav() throws IOException{
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Access-Control-Allow-Origin","*");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();		
		List<Category> list = categoryService.findAll();		
		Map<String,Object> navJson = new HashMap<String,Object>();
		List<String> categoryList = new ArrayList<String>();
	
		for(int i=0;i<list.size();i++){	
			categoryList.add(list.get(i).getCname()+"|"+list.get(i).getCid());
			List<String> categorySecondList = new ArrayList<String>();
			for (CategorySecond str :list.get(i).getCategorySeconds()) {
				categorySecondList.add(str.getCsname()+"|"+str.getCsid());
			}
			navJson.put(list.get(i).getCname()+"|"+list.get(i).getCid(),categorySecondList);
		}		
		navJson.put("category",categoryList);
		GsonBuilder gsonBuilder = new GsonBuilder();
		gsonBuilder.setPrettyPrinting();
		Gson gson = gsonBuilder.create();			
		out.print(gson.toJson(navJson));
		System.out.println(gson.toJson(navJson));
		
	}
	public void  ordinary() throws IOException{
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Access-Control-Allow-Origin","*");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();	
		IndexRec inRec = indexRecService.find();
		
		out.print(inRec.getRecJson().replace(" ",""));
		System.out.println(inRec.getRecJson().replace(" ",""));
	}
}
